package com.example.jn_dxs.Ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.loadable.LoadStatusChangedEvent;
import com.esri.arcgisruntime.loadable.LoadStatusChangedListener;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.example.jn_dxs.Base.BaseFragment;
import com.example.jn_dxs.Base.BaseViewModel;
import com.example.jn_dxs.R;
import com.example.jn_dxs.Ui.activity.StatisticsActivity;
import com.example.jn_dxs.Utlis.TMapLayer;
import com.example.jn_dxs.databinding.FragmentMapBinding;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import me.jessyan.autosize.internal.CancelAdapt;

public class MapFragment extends BaseFragment<BaseViewModel, FragmentMapBinding> implements CancelAdapt {

    private ServiceFeatureTable mServiceFeatureTable;
    private FeatureLayer featureLayer;
    private Callout mCallout;
    private String ID, Address, Lat, Lon, Style, Substance;
    private LocationDisplay mLocationDisplay;

//    private ArcGISTiledLayer tiledLayerBaseMap;
    private GraphicsOverlay mGraphicsOverlay ; //添加点

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_map;
    }

    @Override
    protected void loadData() {

//http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer
        // create new Vector Tiled Layer from service url
        //http://60.208.94.143:6080/arcgis/rest/services/sdmap  /MapServer
        //删除ESRI徽标信息
        binding.MapView.setAttributionTextVisible(false);
        //删除水印  Esri提供了四个ArcGIS Runtime许可级别：Lite，Basic，Standard和Advanced
        ArcGISRuntimeEnvironment.setLicense("runtimelite,1000,rud9605057944,none,C6JC7XLS1HSF8YAJM234");
        mCallout = binding.MapView.getCallout();
        TMapLayer t_vec = TMapLayer.getTMap(TMapLayer.MapType.T_VECTOR_2000);
        String url = "http://60.216.249.11:6080/arcgis/rest/services/LW/LWDHPT/MapServer/2";
        mServiceFeatureTable = new ServiceFeatureTable(url);
        mServiceFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);

//        tiledLayerBaseMap = new ArcGISTiledLayer("https://lbs.amap.com/dev/mapstyle/clone?id=5558b9a42940e8f2002b134fa3a9f1f2");
        featureLayer = new FeatureLayer(mServiceFeatureTable);
        featureLayer.setScaleSymbols(true);
        featureLayer.setLabelsEnabled(true);
        featureLayer.setPopupEnabled(true);
        // set tiled layer as basemap
        Basemap basemap = new Basemap(t_vec);
        // create a map with the basemap
        ArcGISMap map = new ArcGISMap(basemap);
        // create a viewpoint from lat, long, scale  湖北 14.294401,30.596871   济南 36.341667    117.608889    莱芜 117.662538,36.290729
//        Viewpoint viewpoint = new Viewpoint(36.341667, 117.608889, 100000);
//        // set initial map extent
//        map.setInitialViewpoint(viewpoint);
        map.getOperationalLayers().add(featureLayer);
        // set the map to be displayed in this view


        //添加点
        mGraphicsOverlay = new GraphicsOverlay();
        binding.MapView.getGraphicsOverlays().add(mGraphicsOverlay);

        binding.MapView.setMap(map);
        binding.MapView.setOnTouchListener(new DefaultMapViewOnTouchListener(getContext(), binding.MapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                // remove any existing callouts
                if (mCallout.isShowing()) {
                    mCallout.dismiss();
                }
                final com.esri.arcgisruntime.geometry.Point clickPoint = mMapView
                        .screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                // create a selection tolerance
                int tolerance = 10;
                double mapTolerance = tolerance * mMapView.getUnitsPerDensityIndependentPixel();
                // use tolerance to create an envelope to query
                Envelope envelope = new Envelope(clickPoint.getX() - mapTolerance, clickPoint.getY() - mapTolerance,
                        clickPoint.getX() + mapTolerance, clickPoint.getY() + mapTolerance, map.getSpatialReference());
                QueryParameters query = new QueryParameters();
                query.setGeometry(envelope);
                final ListenableFuture<FeatureQueryResult> future = mServiceFeatureTable
                        .queryFeaturesAsync(query, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
                // add done loading listener to fire when the selection returns
                future.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //call get on the future to get the result
                            FeatureQueryResult result = future.get();
                            // create an Iterator
                            Iterator<Feature> iterator = result.iterator();
                            View CallView = View.inflate(getContext(), R.layout.popu_map, null);
                            TextView id = CallView.findViewById(R.id.Id);
                            TextView Location = CallView.findViewById(R.id.Location);
                            TextView Type = CallView.findViewById(R.id.Type);
                            TextView Msg = CallView.findViewById(R.id.Msg);
                            TextView Status = CallView.findViewById(R.id.Status);
                            TextView Detail = CallView.findViewById(R.id.Detail);

                            // cycle through selections
                            Feature feature;
                            while (iterator.hasNext()) {
                                feature = iterator.next();
                                // create a Map of all available attributes as name value pairs
                                Map<String, Object> attr = feature.getAttributes();
                                Set<String> keys = attr.keySet();
                                for (String key : keys) {
                                    Object value = attr.get(key);
                                    // format observed field value as date
//                                    if (value instanceof GregorianCalendar) {
//                                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
//                                        value = simpleDateFormat.format(((GregorianCalendar) value).getTime());
//                                    }
                                    // append name value pairs to TextView

                                    if (key.equals("pkiaa")) {
                                        id.setText("统一编号：" + value);
                                        ID = value.toString();
                                    }
                                    if (key.equals("tkalb")) {
                                        Location.setText("位置：" + value);
                                        Address = value.toString();
                                    }
                                    if (key.equals("swae")) {
                                        Type.setText("监测点类型：" + value);
                                        Style = value.toString();
                                    }
                                    if (key.equals("sweb")) {
                                        Msg.setText("监测内容：" + value);
                                        Substance = value.toString();
                                    }
                                    if (key.equals("swefba")) {
                                        Status.setText("监测井（点）状况：" + value);
                                    }
                                    if (key.equals("lat")) {
                                        Lat = value.toString();  //维度
                                    }
                                    if (key.equals("lon")) {
                                        Lon = value.toString();  //经度
                                    }
//                                    id.append(key + " | " + value + "\n");

                                    Detail.setOnClickListener(v -> {
                                        startActivity(new Intent(getContext(), StatisticsActivity.class).putExtra("id", ID)
//                                                .putExtra("Address", Address)
//                                                .putExtra("Lat", Lat)
//                                                .putExtra("Lon", Lon)
//                                                .putExtra("Style", Style)
//                                                .putExtra("Substance", Substance)
                                        );
                                    });
                                }

                                // center the mapview on selected feature
                                Envelope envelope = feature.getGeometry().getExtent();
                                mMapView.setViewpointGeometryAsync(envelope, 200);
                                // show CallOut
                                mCallout.setLocation(clickPoint);
                                mCallout.setContent(CallView);
                                mCallout.show();
                            }
                        } catch (Exception e) {
                            Log.e(getResources().getString(R.string.app_name), "Select feature failed: " + e.getMessage());
                        }
                    }
                });
                return super.onSingleTapConfirmed(e);
            }
        });
        binding.Vector.setSelected(false);
        binding.Portrait.setSelected(true);

        binding.Vector.setOnClickListener(v -> {
            binding.Vector.setSelected(false);
            binding.Portrait.setSelected(true);
            selectItem(0);
        });
        binding.Portrait.setOnClickListener(v -> {
            binding.Vector.setSelected(true);
            binding.Portrait.setSelected(false);
            selectItem(1);
        });
        binding.Location.setOnClickListener(v -> {
            startLocation();
        });
        startLocation();

    }

    private void selectItem(int position) {


        // update the MapView with the selected vector tiled layer type
//        String vectorTiledLayerUrl = null;
        TMapLayer t_vec;
        switch (position) {
            case 0:
//                vectorTiledLayerUrl = "http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer";
                t_vec = TMapLayer.getTMap(TMapLayer.MapType.T_VECTOR_2000);
                break;

            case 1:
//                vectorTiledLayerUrl = "http://services.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer";
                t_vec = TMapLayer.getTMap(TMapLayer.MapType.T_IMAGE_2000);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + position);
        }
        // create the new vector tiled layer using the url
//        tiledLayerBaseMap = new ArcGISTiledLayer(vectorTiledLayerUrl);
        // change the basemap to the new layer
        binding.MapView.getMap().setBasemap(new Basemap(t_vec));
    }

    private void startLocation() {
        mLocationDisplay = binding.MapView.getLocationDisplay();
        mLocationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER);
        //当我们执行LocationDisplay.startAsync()方法时候，会在地图上显示出我们当前位置
        if (!mLocationDisplay.isStarted())
            mLocationDisplay.startAsync();


        //如果要在LocationDisplay里进行位置信息的自动监听，方法也很简单，只需要LocationDisplay.addLocationChangedListener即可
        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location = locationChangedEvent.getLocation();

                Log.e("xyh", "onLocationChanged: " + location.getPosition().toString());
            }
        });
    }
    //添加点
    private void createPointGraphics() {
        com.esri.arcgisruntime.geometry.Point point = new com.esri.arcgisruntime.geometry.Point(117.608889, 36.341667, SpatialReferences.getWgs84());
        SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.rgb(226, 119, 40), 10.0f);
        pointSymbol.setOutline(new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 2.0f));
        Graphic pointGraphic = new Graphic(point, pointSymbol);
        mGraphicsOverlay.getGraphics().add(pointGraphic);
    }
    @Override
    public void onPause() {
        if (binding.MapView != null) {
            binding.MapView.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (binding.MapView != null) {
            binding.MapView.resume();
        }
    }

    @Override
    public void onDestroy() {
        if (binding.MapView != null) {
            binding.MapView.dispose();
        }
        super.onDestroy();
    }

}
